<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加位置</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=6th98eUmc9jhnForAbNFoOpYiTddATYV"></script>
    <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
    <!-- uni-app JSSDK -->
    <script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@latest/index.js"></script>
	<style>
        html, body { height: 100%; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }
        .container { display: flex; flex-direction: column; height: 100vh; }
        .header { background-color: #f8f8f8; padding: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .search-box { display: flex; align-items: center; }
        #keyword { flex-grow: 1; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px; }
        #search-btn { padding: 8px 16px; margin-left: 10px; border: none; background-color: #007aff; color: white; border-radius: 4px; cursor: pointer; }
        #map { flex-grow: 1; width: 100%; display: none; /* 默认不显示地图，只显示列表 */ }
        #results { flex-grow: 1; overflow-y: auto; background-color: #fff; }
        .result-item { padding: 12px 15px; border-bottom: 1px solid #f0f0f0; cursor: pointer; }
        .result-item:hover { background-color: #f9f9f9; }
        .result-item .name { font-size: 16px; color: #333; font-weight: 500; margin-bottom: 4px; }
        .result-item .address { font-size: 14px; color: #888; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="search-box">
                <input type="text" id="keyword" placeholder="搜索位置" />
                <button id="search-btn">搜索</button>
            </div>
        </div>
        <div id="map"></div>
        <div id="results"></div>
    </div>

    <script type="text/javascript">
        // 辅助函数：从URL获取查询参数
        function getQueryVariable(variable) {
			
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) { return decodeURIComponent(pair[1]); }
            }
            return(false);
        }

	
        let currentResults = []; // 用于存储当前搜索结果

        // 当用户点击一个POI时调用
        function selectPoi(index) {
            const poi = currentResults[index];
			
            if (!poi) return;
            
            // 准备回传给 uni-app 的数据结构
            const locationInfo = {
                // name: poi.title,
                // address: poi.address,
                // latitude: poi.point.lat,
                // longitude: poi.point.lng,
                // // 附加信息
                // city: poi.city,
                // uid: poi.uid,
				...poi
            };
            console.log("locationInfo",typeof uni,locationInfo);
            
			
			// 确保 uni 对象存在后再调用
			if (window.uni && uni.postMessage) {
				console.log("触发postMessage",window.postMessage);

				uni.getEnv(function(env) {
					console.log('当前环境:', env);
		
					if (env.h5) {
						// H5 环境，使用 window.postMessage
						console.log("正在使用 window.postMessage 发送数据");
						// 第一个参数是数据，第二个参数是目标源，'*' 表示任意源
						window.parent.postMessage({
							type: 'message', // H5 postMessage 的事件类型固定为 'message'
							detail: {
								data: [{ // 模拟 uni.postMessage 的数据结构
									type: 'locationSelected',
									payload: locationInfo
								}]
							}
						}, '*');
		
					} else {
						// App 或其他环境
						console.log("正在使用 uni.postMessage 发送数据");
						uni.postMessage({
							data: {
								type: 'locationSelected',
								payload: locationInfo
							}
						});
					}
				});

			} else {
				console.error('uni.postMessage is not available.');
			}
        }
		
		function renderResults(pois) {
			const resultsPanel = document.getElementById('results');
			resultsPanel.innerHTML = '';
			currentPoiResults = pois;
			
			pois.forEach((poi, index) => {
				var item = document.createElement('div');
				item.className = 'result-item';
				item.innerHTML = `<div class="item-info"><div class="item-name">${poi.title}</div><div class="item-address">${poi.address}</div></div>`;
				item.onclick = function() { selectPoi(index); };
				resultsPanel.appendChild(item);
			});

			if (pois.length === 0) {
				 resultsPanel.innerHTML = '<div class="result-item"><div class="item-name">未找到相关结果</div></div>';
			}
		}
		
        document.addEventListener('UniAppJSBridgeReady', function() {
            var lat = parseFloat(getQueryVariable('lat')) || 33.53406453092053;
            var lng = parseFloat(getQueryVariable('lng')) || 119.1405942203101;
            var currentCity = "淮安市"; // 默认城市，后面会尝试通过定位更新
            
            var map = new BMapGL.Map("map");
            var point = new BMapGL.Point(lng, lat);
			
			
            map.centerAndZoom(point, 15);


			console.log("point",map.centerAndZoom(point, 15),point,map);
            var resultsPanel = document.getElementById('results');
            
            // 搜索完成后的回调函数
            var onSearchComplete = function(results){
				console.log("results",results);
                resultsPanel.innerHTML = ''; // 清空旧结果
                currentResults = []; // 清空缓存的结果
                
                if (localSearch.getStatus() == BMAP_STATUS_SUCCESS){
                    let pois = [];
                    for (var i = 0; i < results.getCurrentNumPois(); i ++){
                        pois.push(results.getPoi(i));
                    }
                    currentResults = pois; // 缓存新结果
                    
                    pois.forEach((poi, index) => {
                        var item = document.createElement('div');
                        item.className = 'result-item';
                        item.innerHTML = `<div class="name">${poi.title}</div><div class="address">${poi.address}</div>`;
                        // 关键：为每个列表项添加点击事件
                        item.onclick = function() { selectPoi(index); };
                        resultsPanel.appendChild(item);
                    });
                } else {
                    resultsPanel.innerHTML = '<div class="result-item"><div class="name">未找到相关结果</div></div>';
                }
            }
            
            var localSearch = new BMapGL.LocalSearch(map, {
                onSearchComplete: onSearchComplete
            });

            // 绑定搜索按钮事件
            document.getElementById('search-btn').onclick = function() {
                var keyword = document.getElementById('keyword').value;
                if(keyword.trim()){
                    localSearch.search(keyword);
                }
            };
            
            // 页面加载后，自动搜索"美食、景点、酒店"等附近的POI
            localSearch.searchNearby("景点", point, 1000); // 搜索中心点1公里内的POI
        });
		
    </script>
</body>
</html>
